angular.module('starter.controllers', [])
.controller('lrTabsCtrl', [
  '$scope','$BaseInfo','$AreaInfo','Announces','$OrgInfo',
  function ($scope,$BaseInfo, $AreaInfo,$OrgInfo) {
	$BaseInfo.init();
    $AreaInfo.init();//初始化区域列表
	$OrgInfo.init();//初始化组织架构信息
}])
//登录
.controller('LoginCtrl',['$scope', '$state', '$timeout', 'md5', '$BPTopAlert', '$BPHttp', 'ApiUrl', 'UserInfo','$IM','Announces','$BPLocals','$ionicModal','$ionicLoading','$jpushService','$cordovaToast',
    function ($scope, $state, $timeout, md5, $BPTopAlert, $BPHttp, ApiUrl, UserInfo, $IM ,Announces,$BPLocals,$ionicModal,$ionicLoading,$jpushService,$cordovaToast) {
        $scope.data = {};
		$scope.doForget=function()
		{
			$scope.userinfo = {};
			$ionicModal.fromTemplateUrl(('templates/forget.html'), {
            scope: $scope,
            animation: 'lr-slide-in-right'
			}).then(function (modal) {
				$scope.forgetModal = modal;
				$scope.forgetModal.show();
			});
		};
		$scope.closeForgetModel=function()
		{
			$scope.forgetModal.remove();
		};
		$scope.doForgetUserInfoSubmit=function()
		{
			if ($scope.userinfo.mobile == undefined || $scope.userinfo.mobile == "") {
                $BPTopAlert.show({ text: "请输入手机号码" });
                return false;
            }
            if ($scope.userinfo.userid == undefined || $scope.userinfo.userid == "") {
                $BPTopAlert.show({ text: "请输入账号" });
                return false;
            }
			$ionicLoading.show();
			$BPHttp.post({
                "url": ApiUrl.forgetPasswordApi,
                "data": { "telno": $scope.userinfo.mobile, "username": $scope.userinfo.userid },
                "success": function (data) {
                   $ionicLoading.hide();
				   if (data.status.code != 0) {
					   $BPTopAlert.show({ text: data.status.desc });
				   }
				   else{
					   $BPTopAlert.show({ text: "密码重置成功,请留意短信接收" });
				   }
                },
                "error": function () {
                    $ionicLoading.hide();
                    $BPTopAlert.show({ text: "通信失败" });
                }
            });
			
		};
		$scope.isEmpty = function(obj)
		{
			for (var name in obj)
			{
				return false;
			}
			return true;
		};
		
		if(!$scope.isEmpty($BPLocals.getObject('UserLogin')))
		{
			$scope.data=$BPLocals.getObject('UserLogin');
			
		}

        $scope.logining = false;
        $scope.doLogin = function () {
            if ($scope.data.username == undefined || $scope.data.username == "") {
                $BPTopAlert.show({ text: "请输入账号" });
                return false;
            }
            if ($scope.data.password == undefined || $scope.data.password == "") {
                $BPTopAlert.show({ text: "请输入密码" });
                return false;
            }
            $scope.logining = true;
            $BPHttp.post({
                "url": ApiUrl.loginApi,
                "data": { "password": md5.createHash($scope.data.password), "username": $scope.data.username },
                "success": function (data) {
                    $scope.logining = false;
					$BPLocals.setObject('UserLogin', $scope.data);
                    if (data.status.code != 0) {
                        $BPTopAlert.show({ text: data.status.desc });
                    }
                    else {
                        UserInfo.set(data.result, data.token, true);
                        //$scope.data.password = "";
                        //登录成功连接即时通讯
                        //$IM.init().then(function (data) {console.log(data) });
						$scope.userinfo=UserInfo.get();
						
						if($jpushService.check()){
							
							var tagArr=[];
							$cordovaToast.showLongBottom('登陆成功，当前用户信息：'+$scope.userinfo.account).then(function(success) {
							// success
							}, function (error) {
							// error
							});
							tagArr.push($scope.userinfo.account);
							$jpushService.setTagsWithAlias(tagArr,null);
							//$jpushService.init(config);
						}
						else{
							console.log("服务检测失败");
						}
						
						
						
						$state.go("tab.home");
					
					
						
						//$state.go('messageDetail',{flowId:'3ab05913-1239-4f23-9c9d-085ed1a5ed23',msg:'测试数据'});
						
						
                        
                    }
                },
                "error": function () {
                    $scope.logining = false;
                    $BPTopAlert.show({ text: "通信失败" });
                }
            });
        };
}])
.controller('messageDetailCtrl', ['$state','$scope','$stateParams','$ionicLoading','$ionicPopup','$BPHttp','$BPFlowStartMethod','$BPTopAlert','UserInfo','$BPPageModal','$BPFormPageModal','ApiUrl','$BPSelectModal','$cordovaToast','$cordovaDevice',
 function ($state,$scope,$stateParams,$ionicLoading,$ionicPopup,$BPHttp,$BPFlowStartMethod,$BPTopAlert,UserInfo,$BPPageModal,$BPFormPageModal,ApiUrl,$BPSelectModal,$cordovaToast,$cordovaDevice) {
	if($cordovaDevice.getPlatform()!="Android")
	{
		window.JPush.getApplicationIconBadgeNumber(function(badgeNum) {
		  if(badgeNum-1>=0)
		  {	
			window.plugins.jPushPlugin.setBadge(badgeNum-1);
			window.plugins.jPushPlugin.setApplicationIconBadgeNumber(badgeNum-1);
		  }
		  else{
			window.plugins.jPushPlugin.setBadge(0);
			window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);
		  }
		});
		
	}
    $scope.userinfo = UserInfo.get();
	$scope.ShowNodeRejectStep=0;
    $scope.isFlow = true;
	if($scope.plush.flowId=="")
		$scope.isFlow = false;
	$scope.openMessageModal=function(){
		if($scope.plush.flowId!=undefined)
		{
			$ionicLoading.show();
			$BPHttp.post({
              "url": ApiUrl.getflowProcessListApi,
              "data": { "flowid": $scope.plush.flowId},
              "isverify": true,
              "success": function (data) {
				  
                  var flow = data.result;
				  if(flow.activityId){
					  $scope.editData = flow;
					  $scope.editData.createUserName=flow.createUserName;
					  $scope.editTitle = "流程审批";
					  if ($scope.editModal != undefined) {
						$scope.editModal.remove();
					  }
					  try{
						$BPFlowStartMethod.openFlowEditModal($scope,flow);
					  }
					  catch (ex) {  
						 $cordovaToast.showLongBottom('错误提示：'+ex.message).then(function(success) {
						// success
						}, function (error) {
						// error
						});
					  } 
				  }
				  else{
					  $BPTopAlert.show({ text: "当前待办已经处理" });
				  }
              },
              "error": function () {
				  $ionicLoading.hide();
                  $BPTopAlert.show({ text: "流程信息获取失败" });
              },
              "finally": function () {
                  
              }
          });
		}
	}
	$scope.closeEditModal= function () {
        //关闭当前窗口
		if ($scope.editModal != undefined) {
			$scope.editModal.remove();
		}
    };
    $scope.doRefresh = function () {
        //关闭当前窗口
		
    };
	$scope.NodeRejectStep=[];
    $scope.openEditModal = function (flow) {
      $scope.editData = flow;
      $scope.editTitle = "流程审批";
      if ($scope.editModal != undefined) {
        $scope.editModal.remove();
      }
	  $BPFlowStartMethod.openFlowEditModal($scope,flow);
    };
	
    	
	$scope.closeEditModal=$BPFormPageModal($scope,true);
	$scope.checkNodeRejectStep= function(){
		return $scope.editData.VerificationFinally=="驳回"&&$scope.NodeRejectStep.length>0&&$scope.ShowNodeRejectStep==1;
	};
    $scope.isInputActive = function (name) {
			return ($scope.editData[name] != null && $scope.editData[name] != "" && $scope.editData[name] != undefined);
    };
    // 审核
    $scope.flowVerificationSideList = [
        { text: "发送", value: "发送", bgColor:"bgcolor_a" },
        { text: "终止", value: "终止", bgColor:"bgcolor_b" },
        { text: "驳回", value: "驳回", bgColor:"bgcolor_c" },
		{ text: "移交", value: "移交", bgColor:"bgcolor_d" }
    ];

	$scope.openFlowNodeRejectStepModal = function () {
       $BPSelectModal({
			title:"驳回步骤",
			bgAllColor:"positive-bg",
			selectValue:$scope.editData.NodeRejectStep,
			text:"name",
			value:"id",
			data:$scope.NodeRejectStep,
			onChange: function (item) {
			  $scope.editData.NodeRejectStep = item.value;
			  $scope.editData.NodeRejectSteptext = item.text;
			}
	    });
    };
	
    $scope.openFlowVerificationModal = function () {
       $BPSelectModal({
			title:"审核意见",
			bgAllColor:"positive-bg",
			selectValue:$scope.editData.VerificationFinally,
			text:"text",
			value:"value",
			data:$scope.flowVerificationSideList,
			onChange: function (item) {
			  //$scope.editData.VerificationFinally = item.value;
			  $scope.editData.VerificationFinally = item.text;
			}
	    });
    };

    $scope.doSubmit = function (type) {
		$BPFlowStartMethod.VerificationForm($scope,type);
    }
	
	
}])
//主页
.controller('HomeCtrl', [
    '$scope','UserInfo','$interval','$BPPageModal','$BaseInfo','HomeApps','Announces','$BPHttp', 'ApiUrl','$ionicModal','$BPFormatDate','$ionicLoading','$BPTriggerRefresh','$FormData','$timeout','$BPDataIsAll','$BPPopup','$BPFormDesign','$BPFormMethod','$BPFormPageModal','$jpushService','$cordovaToast','$timeout',
  function ($scope,UserInfo,$interval,$BPPageModal,BaseInfo, HomeApps, Announces,$BPHttp, ApiUrl,$ionicModal,$BPFormatDate,$ionicLoading,$BPTriggerRefresh,$FormData,$timeout,$BPDataIsAll,$BPPopup,$BPFormDesign,$BPFormMethod,$BPFormPageModal,$jpushService,$cordovaToast,$timeout) {
    
	/*
	$timeout(function () {
		  $scope.plush={};

		  $scope.plush.message="1111";
		  $scope.plush.flowId="2b12a1ba-e1ff-4bce-8a2f-aae5934b01af";
		  $scope.openPageModel("flowMessageDetails.html");
    }, 1000);*/
	
	$ionicLoading.show();
	$scope.homeApps=[];
	$scope.userinfo=UserInfo.get();
	$interval(function () {
		if (UserInfo.get().isLogin == true){
			$scope.doRefreshFlow();
		}
    }, 4000);
	//推送初始化
	var setTagsWithAliasCallback=function(event){
	   //$cordovaToast.showLongBottom('推送服务注册完毕，tags'+event.tags).then(function(success) {
		// success
	   //}, function (error) {
		// error
	   //});
		//window.alert('result code:'+event.resultCode+' tags:'+event.tags+' alias:'+event.alias);
	}
	var receiveNotificationIniOSCallback=function(data){
		var json=data;
		if(typeof data === 'string'){
			json=JSON.parse(data);
		}
		  var message = json.aps.alert;
		  //window.plugins.jPushPlugin.prototype.setBadge();
		  if($scope.pageModel!=null)
		  {
			  $scope.pageModel.remove();
		  }
		  if($scope.editModal!=null)
		  {
			  $scope.editModal.remove();
		  }
		  if($scope.searchModal!=null)
		  {
			  $scope.searchModal.remove();
		  }
		  if($scope.rptModal!=null)
		  {
			  $scope.rptModal.remove();
		  }
		  if($scope.listModal!=null)
		  {
			  $scope.listModal.remove();
		  }
		  if($scope.listModal!=null)
		  {
			  $scope.listModal.remove();
		  }
		  $scope.plush={};

		  $scope.plush.message=message;
		  if(json.flowid){
			   var id=json.flowid;
			   $scope.plush.flowId=id;
		  }
		  else{
			  $scope.plush.flowId="";
		  }
		  
		  $scope.openPageModel("flowMessageDetails.html");
	};
	var openNotificationInAndroidCallback=function(data){
		  var json=data;
		  //window.alert(json);
		  if(typeof data === 'string'){
			json=JSON.parse(data);
		  }
		  
		  var message = json.extras['cn.jpush.android.ALERT'];
		  //为了避免被其他层档住要先清掉其他层
		  //为了避免被其他层档住要先清掉其他层
		  if($scope.pageModel!=null)
		  {
			  $scope.pageModel.remove();
		  }
		  if($scope.editModal!=null)
		  {
			  $scope.editModal.remove();
		  }
		  if($scope.searchModal!=null)
		  {
			  $scope.searchModal.remove();
		  }
		  if($scope.rptModal!=null)
		  {
			  $scope.rptModal.remove();
		  }
		  if($scope.listModal!=null)
		  {
			  $scope.listModal.remove();
		  }
		  if($scope.listModal!=null)
		  {
			  $scope.listModal.remove();
		  }
		  $scope.plush={};

		  $scope.plush.message=message;
		  if(json.extras.flowid){
			   var id=json.extras.flowid;
			   $scope.plush.flowId=id;
		  }
		  else{
			  $scope.plush.flowId="";
		  }
		  $scope.openPageModel("flowMessageDetails.html");
		  //$state.go('messageDetail',{flowId:id,msg:alert}); 
	};
	var config={
	  stac:setTagsWithAliasCallback,
	  AndroidCallback:openNotificationInAndroidCallback,
	  IOSCallback:receiveNotificationIniOSCallback
	};
	if($jpushService.check()){
		//var tagArr=[];
		//$cordovaToast.showLongBottom('推送服务注册完毕，账号信息：'+$scope.userinfo.account).then(function(success) {
		// success
	    //}, function (error) {
		// error
	    //});
		//tagArr.push($scope.userinfo.account);
		//$jpushService.setTagsWithAlias(tagArr,null);
		$jpushService.init(config);
	}
	else{
		console.log("服务检测失败");
	}
	
	
	
	
	
	$BPHttp.post({
	  "url": ApiUrl.getAnnouncesListApi,
	  "isverify": true,
	  "success": function (data) {
		  //$scope.logining = false;
		  $scope.modules= JSON.parse(data.result.message);
		  $scope.homeApps = HomeApps.all();
		  $scope.homeApps[0].props=0;
		  for (var i in $scope.modules){
			  $scope.homeApps.push(
			  {
				  name: $scope.modules[i].name,
				  icon: $scope.modules[i].icon,
				  color: $scope.modules[i].color,
				  viewid: $scope.modules[i].viewid,
				  id : $scope.modules[i].id
			  });
		  }
		  
		  $scope.announces= data.result.rows;
		  $scope.doRefreshFlow();
		  $ionicLoading.hide();
        },
	  "finally": function () { 
			$ionicLoading.hide();
	  }
    });
	$scope.doRefreshFlow = function () {
		$BPHttp.post({
		  "url": ApiUrl.flowProcessCountApi,
		  "isverify": true,
		  "success": function (data) {
			  $scope.homeApps[0].props=data.status.desc;
			}
		});
		$BPHttp.post({
		  "url": ApiUrl.getAnnouncesListApi,
		  "isverify": true,
		  "success": function (data) {
			  $scope.announces= data.result.rows;
			},
		  "finally": function () { 
				
		  }
		});
    };
	$scope.openPageModelSelf = function (viewid,id,title) {
		$scope.id=id;
		$scope.dbData={};
		$scope.frmEntity={};
		//console.log(id);
		if(id==""){
			$scope.openPageModel(viewid);
		}
		else{
			//home-flow.html 代表流程
			//获取数据
			$ionicLoading.show();
			$BPHttp.post({
				  "url": ApiUrl.geFormContentApi,
				  "data": {
					  formRelationId: id.toString()
				  },
				  "isverify": true,
				  "success": function (redata) {
					  //开始解析数据
					  var frmfield=redata.result.frmField;
					  var frmEntity=redata.result.frmEntity;
					  var isFlow=redata.result.isFlow;
					  var isFlowShow=redata.result.isFlowShow;
					  $scope.frmEntity=frmEntity;
					  var r = [], filter_id;
					  if (frmfield != null)
						filter_id = JSON.parse(frmfield).map(function (item) { if (item.app) return item.fieldid; });
					  else
						filter_id="";
					  
					  var frmJson = JSON.parse(frmEntity.frmContent);
					  r.push({
							label: "CustmerFormId",
							name: "CustmerFormId",
							hidden:true
					  });
					  r.push({
							label: "创建人",
							name: "CreateUser_Name",
							hidden: false
					  });
					  r.push({
							label: "部门",
							name: "CreateUser_DepInfo",
							hidden: false
					  });
					  var tj=0;
					  for (var j = 0; j < frmJson.data.length; j++) {
						for(var count=0;count<frmJson.data[j].fields.length;count++)
						{
							var item=frmJson.data[j].fields[count];
							var index_1 = filter_id.indexOf(item.field);
							if (filter_id == "") index_1 = 0;
							if (index_1 >= 0) {
								if(item.type != "upload" && item.type != "image" && item.type != "messageInfo" && item.type != "multiupload" && item.type != "image")
								{
									//item.field = (frmJson.type == 1 ? item.field : item.field.replace(/-/g, ""));
									if(frmJson.type == 0)
										item.field="f"+tj;
									r.push({
										label: item.label,
										name: item.field,
										hidden:false
									});
								}
							}
							tj++;
						}					  
					  }
					  
					  if(isFlow==1)
					  {
						  r.push({
							label: "当前节点",
							name: "ActivityName",
							hidden: false
						  });
					  }
					  //生成页面模板
					  var html='<ion-modal-view>';
					  html+='<ion-header-bar class="bar-stable nav-bar-block nav-title-slide-ios7">';
					  html+='<button class="button button-clear " ng-click="closeListModal()"><i class="icon ion-ios-arrow-left"></i></button>';
					  html+='<h1 class="title">'+title+'</h1>';
					  html+='<button class="button button-clear" ng-click="openSearch()"><i class=" icon ion-ios-search "></i></button>';
					  html+='</ion-header-bar>';
					  html+='<div class="bar bar-subheader lr-subheader">';
					  html+='<div class="lr-left-tool">';
					  html+='<div class="lr-down-select"><span>全部</span><span class="num">{{data.records}}条</span><span><i class="icon ion-ios-arrow-down"></i></span></div>';
					  html+='</div>';
					  html+='</div>';
					  
					  
					  html+='<ion-content delegate-handle="formlist-content">';
					  html+='<ion-refresher pulling-text="下拉刷新" on-refresh="doRefresh()"></ion-refresher>';
					  html+='<div class="list  list-inset lr-list-type2" style="margin-top:40px;">';
					  html+='<ion-list>';
					  html+='<ion-item ng-repeat="item in data.items" class="item-remove-animate mt10" ng-click="openDetailsModal(item.CustmerFormId)">';
					  html+='<div class="need_list">';
					  var f=0;
					  for(var s=0;s<r.length;s++){
						  if(!r[s].hidden)
						  {
							 html+='<h2><span>['+r[s].label+']</span>{{item.'+r[s].name+'}}</h2>';
							 f=s;
							 break;
						  }
					  }
					 

					  html+='<ul class="need_ul">';
					  for(var s=0;s<r.length;s++){
						  if(!r[s].hidden&&f!=s)
						  {
								html+='<li><span>'+r[s].label+'：</span><em>{{item.'+r[s].name+'}}</em></li>';
						  }
					  }
					  html+='</ul>';
					  html+='</div>';
					  if(isFlow!=1)
						html+='<ion-option-button ng-click="doDelete(item)"><span class="lr-trash-circled"><i class="icon ion-ios-trash-outline"></i></span></ion-option-button>';
					  
					  html+='</ion-item>';
					  html+='</ion-list>';
					  html+='</div>';
					  html+='<ion-infinite-scroll ng-if="data.moredata" on-infinite="doLoadMore()" distance="1%"></ion-infinite-scroll>';
					  html+='</ion-content>';
					  if(isFlow!=1)
					  {
						  html+='<div class="lr-plug-btn">';
						  html+='	  <i class=" icon ion-ios-plus positive" ng-click="openEditModal(\'\')"></i>';
						  html+='</div>';
					  }
					  html+='</ion-modal-view>';
					  
					  
					  $scope.title=title;
					  
					  $scope.data = $FormData.getList(id.toString());
					  $scope.data.items=[];
					  $scope.data.records=0;
					  //刷新数据
					  $timeout(function () {
					    $BPTriggerRefresh.triggerRefresh('formlist-content');
					  },400);
					  $scope.doRefresh = function () {
						 $FormData.update(id.toString(),function () {$scope.$broadcast('scroll.refreshComplete');});
					  };
					  $scope.doLoadMore = function () {
					     $FormData.add(id.toString(),function () {$scope.$broadcast('scroll.infiniteScrollComplete');});
					  };
					  //搜索页
					  $scope.closeSearchModal = function () {
					      $scope.searchModal.remove();
					  };
					  
					  //打开新建表单
					  $scope.openEditModal=function(itemid){$BPFormMethod.openEditModal($scope,frmJson,title,itemid);};
					  /*
					  //区域选择
					  $scope.openAreaSelectModal=function(dataType,field){$BPFormMethod.openAreaSelectModal($scope,dataType,field);};
					  //文件下载
					  $scope.getFileContents=function(file){$BPFormMethod.getFileContents($scope,file);};
					  //图片预览
					  $scope.showImageModal = function(url) {$BPFormMethod.showImageModal($scope,url);}
					  //角色选择、部门选择、岗位选择、用户选择
					  $scope.openBaseSelectModal=function(dataType,field){$BPFormMethod.openBaseSelectModal($scope,dataType,field);};
					  //删除文件
					  $scope.doDeleteFile=function(file,field){$BPFormMethod.doDeleteFile($scope,file,field);};
					  //文件选择
					  $scope.openFileSelectModal=function(type,field){$BPFormMethod.openFileSelectModal($scope,type,field);};
					  //多选项目
					  $scope.openCheckboxModal=function (dataSource,defaultValue,title,field,dataItemCode,dbId,dbTable,dbFiledValue,dbFiledText) {$BPFormMethod.openCheckboxModal($scope,dataSource,defaultValue,title,field,dataItemCode,dbId,dbTable,dbFiledValue,dbFiledText);};
					  //单选项目
					  $scope.openRadioModal= function (dataSource,defaultValue,title,field,dataItemCode,dbId,dbTable,dbFiledValue,dbFiledText) {$BPFormMethod.openRadioModal($scope,dataSource,defaultValue,title,field,dataItemCode,dbId,dbTable,dbFiledValue,dbFiledText);};
					  //客户选择
					  $scope.openCrmModal=function (title,field){$BPFormMethod.openCrmSelectModal($scope,title,field);};
					  */
					  //打开详情
					  $scope.openDetailsModal=function(CustmerFormId){
						  //数据详情
						  if(isFlow!=1)
						  {
							  $BPFormMethod.openDetailsModal($scope,frmJson,title,CustmerFormId);
							  //console.log("选择的id"+CustmerFormId);
						  }
						  else{
							  //加载流程数据
							  //$ionicLoading.show();
							  $BPFormMethod.openFlowDetailsModal($scope,frmJson,title,CustmerFormId);
						  }
					  };

					  
					  //删除
					  $scope.doDelete = function (Item) {
						$BPPopup.confirm({
							title: '<p> </p>确定要删除?<p> </p>',
							okText: '删除',
							ok: function () {
							  $BPFormMethod.removeItem($scope,Item);
							}
						});
					  };
					  
					  $scope.doSubmit=function(CustmerFormId){
						  $BPFormMethod.dosubmit($scope,CustmerFormId);				   
					  };
					  $scope.closeDetailsModal=function () {
						  $scope.editModal.remove();
					  };
					  $scope.closeEditModal=$BPFormPageModal($scope,true);
					  
					  
					  $scope.openSearch = function () {
						  $scope.searchData={};
						  $BPFormMethod.openSearch($scope,$FormData,id,isFlow,r);
					  };
					  
					  
					  $scope.doSearch = function () {
						  $FormData.searchData(id.toString());
					  };
					  $scope.loadMoreSearch = function () {
						  $FormData.searchDataAdd(id.toString(),function () {
							$scope.$broadcast('scroll.infiniteScrollComplete');
						  });
					  };
					  $scope.closeListModal = function () {
						  $scope.listModal.remove();
					  };
					  
					  var listmodal=$ionicModal.fromTemplate(html, {
							 scope: $scope,
							 animation: 'slide-in-up',
					  });
					   $scope.listModal = listmodal;
					   $scope.listModal.show();
					  
				  },
				  "finally": function () { 
						$ionicLoading.hide();
				  }
			});
			
			
		}
	};
	
	//打开详情页
    $scope.openNoticesModal = function (noticeTitle,noticeContent,noticeTime) {
		var arrEntities={'lt':'<','gt':'>','nbsp':' ','amp':'&','quot':'"'};
		noticeContent=noticeContent.replace(/&(lt|gt|nbsp|amp|quot);/ig,function(all,t){return arrEntities[t];});
		$scope.noticeContent = noticeContent;
		$scope.noticeTitle = noticeTitle;
		$scope.title="公告详情";
		$scope.noticeDateTime =  $BPFormatDate(noticeTime, "yyyy-MM-dd hh:mm");
        $ionicModal.fromTemplateUrl(('templates/notices/noticeDetails.html'), {
            scope: $scope,
            animation: 'lr-slide-in-right'
        }).then(function (modal) {
            $scope.noticesModal = modal;
            $scope.noticesModal.show();
        });
    };
    $scope.closeNoticesModal = function () {
        $scope.noticesModal.remove();
    };
    //打开应用列表
    $scope.closePageModel =  $BPPageModal($scope,'templates/homeApps/',null,function () {$scope.doRefreshFlow();});
  }])
//流程信息获取列表
.controller('WorkflowCtrl', [
    '$scope', '$BPPageModal', '$WFlows','ApiUrl','$BPHttp',
  function ($scope, $BPPageModal, $WFlows,ApiUrl,$BPHttp) {
    $scope.wflows = $WFlows.all();
	//$scope.props=0;
	$scope.doRefresh = function () {
		$BPHttp.post({
		  "url": ApiUrl.flowProcessCountApi,
		  "isverify": true,
		  "success": function (data) {
			  $scope.wflows["befProcess"].props=data.status.desc;
			}
		});
    };
	console.log($scope.wflows);
	$scope.doRefresh();
    $scope.closeFlowPageModel = $BPPageModal($scope, 'templates/homeApps/workflow/',null,function () {$scope.doRefresh();});
}])
//发起流程
.controller('flowDesignCtrl', [
    '$scope', '$timeout','$BPTriggerRefresh','$ionicModal','$BPDataIsAll','$BPTopAlert','$ionicLoading', '$FlowDesigns','$BPHttp','ApiUrl','$BPFormDesign','$BPGetDataItem','$BPSelectModal','$BPCheckboxModal','$BPGetDataTable','$ionicPopup','$BPFormatDate','$BPPopup','$BPFormMethod','$BPFlowStartMethod','$BPFormPageModal',
  function ($scope, $timeout, $BPTriggerRefresh,$ionicModal,$BPDataIsAll,$BPTopAlert,$ionicLoading, $FlowDesigns,$BPHttp,ApiUrl,$BPFormDesign,$BPGetDataItem,$BPSelectModal,$BPCheckboxModal,$BPGetDataTable,$ionicPopup,$BPFormatDate,$BPPopup,$BPFormMethod,$BPFlowStartMethod,$BPFormPageModal) {
    $scope.data = $FlowDesigns.getList();
    //刷新数据
    $timeout(function () {
        $BPTriggerRefresh.triggerRefresh('flowDesignlist-content');
    }, 200);
    $scope.doRefresh = function () {
      $FlowDesigns.update(function () {
          $scope.$broadcast('scroll.refreshComplete');
        });
    };
    $scope.doLoadMore = function () {
      $FlowDesigns.add(function () {
          $scope.$broadcast('scroll.infiniteScrollComplete');
        });
    };

    $scope.openEditModal = function (flow) {
		  $scope.editData={};
		  $scope.editData.flow = flow;
		  if ($scope.editModal != undefined) {
			$scope.editModal.remove();
		  }
		//加载数据
		$scope.editData.CustomName=flow.schemename;
		$scope.editData.wflevel = "2";
		$scope.editData.wfleveltext = "普通";
		$scope.editData.type = "0";
		$scope.editData.typetext = "直接发送";
		$BPFlowStartMethod.openFlowStartModal($scope,flow.id.toString());
	  
    };
    $scope.closeEditModal=$BPFormPageModal($scope,true);
    $scope.isInputActive = function (name) {
      return ($scope.editData[name] != null && $scope.editData[name] != "" && $scope.editData[name] != undefined);
    };
	
	
    
    $scope.doSubmit = function () {
		$BPFlowStartMethod.dosubmit($scope);
    };
}])
//草稿流程
.controller('flowRoughdraftCtrl', [
    '$scope', '$timeout', '$BPHttp', '$BPTopAlert', '$BPTriggerRefresh', '$BPPopup','ApiUrl', '$FlowRoughdrafts','$BPFlowStartMethod','$BPFormPageModal','$ionicPopup',
  function ($scope, $timeout, $BPHttp, $BPTopAlert, $BPTriggerRefresh, $BPPopup, ApiUrl, $FlowRoughdrafts,$BPFlowStartMethod,$BPFormPageModal,$ionicPopup) {
    $scope.dat = $FlowRoughdrafts.getList();
	$scope.searchData={};
	$scope.searchData.Keyword="";
	$FlowRoughdrafts.setInit();
    //刷新数据
    $timeout(function () {
        $BPTriggerRefresh.triggerRefresh('flowRoughdraftlist-content');
    }, 200);
    $scope.doRefresh = function () {
        $FlowRoughdrafts.update(function () {
            $scope.$broadcast('scroll.refreshComplete');
        });
    };
	$scope.openDetailsModal=function(flow){
		//草稿编辑
		$scope.editData = flow;
		$scope.editTitle = "流程草稿";
		if ($scope.editModal != undefined) {
			$scope.editModal.remove();
		}
		$BPFlowStartMethod.openFlowRoughdraftModal($scope,flow);
	};
    $scope.doLoadMore = function () {
        $FlowRoughdrafts.add(function () {
            $scope.$broadcast('scroll.infiniteScrollComplete');
        });
    };
	
	$scope.isInputActive = function (name) {
      return ($scope.editData[name] != null && $scope.editData[name] != "" && $scope.editData[name] != undefined);
    };
	$scope.closeEditModal=$BPFormPageModal($scope,true);
    //删除
    $scope.doDelete = function (flow) {
        $BPPopup.confirm({
            title: '<p> </p>确定要删除?<p> </p>',
            okText: '删除',
            ok: function () {
              $FlowRoughdrafts.remove(flow);
                if($scope.detailsModal != null) {
                  $scope.detailsModal.remove();
                }
            }
        });
    };
	
	$scope.doSubmit = function (type) {
		$BPFlowStartMethod.RoughdraftForm($scope,type);
    }
	
	$scope.openSearch = function () {
		//$scope.searchData = $FlowRoughdrafts.getSearchList();
		//搜索对话框
		var mySearchPopup = $ionicPopup.show({
			 template: '<input type="text" ng-model="searchData.Keyword">',
			 title: '信息搜索',
			 scope: $scope,
			 buttons: [
			   { text: '关闭' },
			   {
				 text: '<b>搜索</b>',
				 type: 'button-positive',
				 onTap: function(e) {
				   if ($scope.searchData.Keyword) {
					 return $scope.searchData.Keyword;
				   }
				 }
			   },
			 ]
	    });
		mySearchPopup.then(function(res) {
			$FlowRoughdrafts.getSearchList(res,function () {
				$scope.$broadcast('scroll.refreshComplete');
			});
		});
    };
	
}])
//我的流程
.controller('flowProcessCtrl', [
    '$scope', '$timeout', '$BPHttp', '$BPTopAlert', '$BPTriggerRefresh','$ionicModal', 'ApiUrl', '$Workflows','$BPFormMethod','$BPFormPageModal','$ionicPopup','$BaseInfo',
  function ($scope, $timeout, $BPHttp, $BPTopAlert, $BPTriggerRefresh,$ionicModal, ApiUrl, $Workflows,$BPFormMethod,$BPFormPageModal,$ionicPopup,$BaseInfo) {
    $scope.dat = $Workflows.getList();
	$scope.searchData={};
	$scope.searchData.Keyword="";
	$Workflows.setInit();
    //刷新数据
    $timeout(function () {
        $BPTriggerRefresh.triggerRefresh('flowProcesslist-content');
    }, 200);
    $scope.doRefresh = function () {
        $Workflows.update(function () {
            $scope.$broadcast('scroll.refreshComplete');
        });
    };
    $scope.doLoadMore = function () {
        $Workflows.add(function () {
            $scope.$broadcast('scroll.infiniteScrollComplete');
        });
    };
    //详情页
    $scope.openDetailsModal = function (flowId,isfinish,title) {
	  //var title="流程信息";
	  var frmJson={};
	  console.log(isfinish);
	  if(isfinish!="被驳回")
	  {
		  $BPFormMethod.openFlowDetailsModal($scope,frmJson,title,flowId);
	  }
	  else{
		  $BPFormMethod.openFlowEditModal($scope,frmJson,title,flowId);
	  }
    };
	
	
	
	$scope.openSearch = function () {
		//$scope.searchData = $FlowRoughdrafts.getSearchList();
		//搜索对话框
		var mySearchPopup = $ionicPopup.show({
			 template: '<input type="text" ng-model="searchData.Keyword">',
			 title: '信息搜索',
			 scope: $scope,
			 buttons: [
			   { text: '关闭' },
			   {
				 text: '<b>搜索</b>',
				 type: 'button-positive',
				 onTap: function(e) {
				   if ($scope.searchData.Keyword) {
					 return $scope.searchData.Keyword;
				   }
				 }
			   },
			 ]
	    });
		mySearchPopup.then(function(res) {
			$Workflows.getSearchList(res,function () {
				$scope.$broadcast('scroll.refreshComplete');
			});
		});
    };
	
	
	
	
	
    $scope.closeDetailsModal=$BPFormPageModal($scope,false);
	
}])
//待办流程
.controller('flowBefProcessCtrl', [
    '$scope', '$timeout', '$BPHttp', '$BPTopAlert', '$BPTriggerRefresh','$ionicModal','UserInfo', 'ApiUrl', '$FlowBefProcesss','$BPDataIsAll','$BPFlowStartMethod','$BPSelectModal','$BPPopup','$BPFormMethod','$BPFormPageModal','$ionicPopup','$ionicLoading',
  function ($scope, $timeout, $BPHttp, $BPTopAlert, $BPTriggerRefresh, $ionicModal,UserInfo, ApiUrl, $FlowBefProcesss,$BPDataIsAll,$BPFlowStartMethod,$BPSelectModal,$BPPopup,$BPFormMethod,$BPFormPageModal,$ionicPopup,$ionicLoading) {
    $scope.searchData={};
	$scope.searchData.Keyword="";
	$FlowBefProcesss.setInit();
	$scope.dat = $FlowBefProcesss.getList();
    $scope.userinfo = UserInfo.get();
	$scope.ShowNodeRejectStep=0;
   //console.log("搜索关键词："+$scope.searchData.Keyword);
	console.log($scope.dat);
	/*console.log(UserInfo.get());
    console.log($FlowBefProcesss.getList());*/
    //刷新数据
    $timeout(function () {
        $BPTriggerRefresh.triggerRefresh('flowBefProcesslist-content');
    }, 200);
	
	
	
    $scope.doRefresh = function () {
        $FlowBefProcesss.update(function () {
            $scope.$broadcast('scroll.refreshComplete');
        });
    };
    $scope.doLoadMore = function () {
        $FlowBefProcesss.add(function () {
            $scope.$broadcast('scroll.infiniteScrollComplete');
        });
    };
	$scope.NodeRejectStep=[];
    $scope.openEditModal = function (flow) {
      $scope.editData = flow;
      $scope.editTitle = "流程审批";
      if ($scope.editModal != undefined) {
        $scope.editModal.remove();
      }
	  $BPFlowStartMethod.openFlowEditModal($scope,flow);
    };
	
    
	//$scope.searchData={};
	$scope.openSearch = function () {
		//$scope.searchData = $FlowRoughdrafts.getSearchList();
		//搜索对话框
		var mySearchPopup = $ionicPopup.show({
			 template: '<input type="text" ng-model="searchData.Keyword">',
			 title: '信息搜索',
			 scope: $scope,
			 buttons: [
			   { text: '关闭' },
			   {
				 text: '<b>搜索</b>',
				 type: 'button-positive',
				 onTap: function(e) {
				   if ($scope.searchData.Keyword) {
					 return $scope.searchData.Keyword;
				   }
				 }
			   },
			 ]
	    });
		mySearchPopup.then(function(res) {
			$FlowBefProcesss.getSearchList(res,function () {
				$scope.$broadcast('scroll.refreshComplete');
			});
		});
    };
	
	
	
	$scope.closeEditModal=$BPFormPageModal($scope,true);
	$scope.checkNodeRejectStep= function(){
		return $scope.editData.VerificationFinally=="驳回"&&$scope.NodeRejectStep.length>0&&$scope.ShowNodeRejectStep==1;
	};
    $scope.isInputActive = function (name) {
			return ($scope.editData[name] != null && $scope.editData[name] != "" && $scope.editData[name] != undefined);
    };
    // 审核
    $scope.flowVerificationSideList = [
        { text: "发送", value: "发送", bgColor:"bgcolor_a" },
        { text: "终止", value: "终止", bgColor:"bgcolor_b" },
        { text: "驳回", value: "驳回", bgColor:"bgcolor_c" },
		{ text: "移交", value: "移交", bgColor:"bgcolor_d" }
    ];

	$scope.openFlowNodeRejectStepModal = function () {
       $BPSelectModal({
			title:"驳回步骤",
			bgAllColor:"positive-bg",
			selectValue:$scope.editData.NodeRejectStep,
			text:"name",
			value:"id",
			data:$scope.NodeRejectStep,
			onChange: function (item) {
			  $scope.editData.NodeRejectStep = item.value;
			  $scope.editData.NodeRejectSteptext = item.text;
			}
	    });
    };
	
    $scope.openFlowVerificationModal = function () {
       $BPSelectModal({
			title:"审核意见",
			bgAllColor:"positive-bg",
			selectValue:$scope.editData.VerificationFinally,
			text:"text",
			value:"value",
			data:$scope.flowVerificationSideList,
			onChange: function (item) {
			  //$scope.editData.VerificationFinally = item.value;
			  $scope.editData.VerificationFinally = item.text;
			}
	    });
    };

    $scope.doSubmit = function (type) {
		$BPFlowStartMethod.VerificationForm($scope,type);
    }
}])
//已办流程
.controller('flowAftProcessCtrl', [
    '$scope', '$timeout', '$BPHttp', '$BPTopAlert', '$BPTriggerRefresh', '$ionicModal', 'ApiUrl', '$FlowAftProcesss','$BPFormMethod','$BPFormPageModal','$ionicPopup',
  function ($scope, $timeout, $BPHttp, $BPTopAlert, $BPTriggerRefresh, $ionicModal, ApiUrl, $FlowAftProcesss,$BPFormMethod,$BPFormPageModal,$ionicPopup) {
    $scope.searchData={};
	$FlowAftProcesss.setInit();
	
	$scope.dat = $FlowAftProcesss.getList();
	
    //刷新数据
    $timeout(function () {
        $BPTriggerRefresh.triggerRefresh('flowAftProcesslist-content');
    }, 200);
    $scope.doRefresh = function () {
        $FlowAftProcesss.update(function () {
            $scope.$broadcast('scroll.refreshComplete');
        });
    };
    $scope.doLoadMore = function () {
        $FlowAftProcesss.add(function () {
            $scope.$broadcast('scroll.infiniteScrollComplete');
        });
    };
    //详情页
    $scope.openDetailsModal = function (flowId,title) {
	  //var title="流程信息";
	  var frmJson={};
	  $BPFormMethod.openFlowDetailsModal($scope,frmJson,title,flowId);
    };

	
	//$scope.searchData={};
	$scope.openSearch = function () {
		//$scope.searchData = $FlowRoughdrafts.getSearchList();
		//搜索对话框
		var mySearchPopup = $ionicPopup.show({
			 template: '<input type="text" ng-model="searchData.Keyword">',
			 title: '信息搜索',
			 scope: $scope,
			 buttons: [
			   { text: '关闭' },
			   {
				 text: '<b>搜索</b>',
				 type: 'button-positive',
				 onTap: function(e) {
				   if ($scope.searchData.Keyword) {
					 return $scope.searchData.Keyword;
				   }
				 }
			   },
			 ]
	    });
		mySearchPopup.then(function(res) {
			$FlowAftProcesss.getSearchList(res,function () {
				$scope.$broadcast('scroll.refreshComplete');
			});
		});
    };
	
	
	
	
	$scope.closeDetailsModal=$BPFormPageModal($scope,false);
	
}])
//工作委托
.controller('flowDelegateCtrl', [
  '$scope', '$timeout', '$BPTriggerRefresh', 'ApiUrl', '$FlowDelegates',
  function ($scope, $timeout, $BPTriggerRefresh, ApiUrl, $FlowDelegates) {
      $scope.dat = $FlowDelegates.getList();
      //刷新数据
      $timeout(function () {
          $BPTriggerRefresh.triggerRefresh('flowDelegatelist-content');
      }, 200);
      $scope.doRefresh = function () {
        $FlowDelegates.update(function () {
            $scope.$broadcast('scroll.refreshComplete');
          });
      };
      $scope.doLoadMore = function () {
        $FlowDelegates.add(function () {
            $scope.$broadcast('scroll.infiniteScrollComplete');
          });
      };

  }])
//图表

.controller('lrChartsCtrl', [
    '$scope','$BPHttp', 'ApiUrl',
  function ($scope, $BPHttp, ApiUrl) {
	$scope.logining = true;
	$BPHttp.post({
                  "url": ApiUrl.getChartsApi,
                  "isverify": true,
                  "success": function (data) {
							var result=JSON.parse(data.status.desc);
						    var ClientList=JSON.parse(result.ClientList);
							var GetCustomerArea=JSON.parse(result.GetCustomerArea);
							var GetOrderType=JSON.parse(result.GetOrderType);
							
							var Data_CustomerArea = [];
							var categories1=[];
							var categories2=[];
							for (var i in GetCustomerArea) {
							  var item = GetCustomerArea[i];
							  var data=[];
							  data.push(item["tj"]);
							  Data_CustomerArea.push([item["client_resource"],item["tj"]]);
						    }
							
							var tj=0;
							for(var i in Data_CustomerArea)
							{
								tj+=Data_CustomerArea[i][1];
							}
							
							
							for(var i in Data_CustomerArea)
							{
								Data_CustomerArea[i][1]=Data_CustomerArea[i][1]/tj*100;
								
								categories1.push(Highcharts.numberFormat(Data_CustomerArea[i][1],2)+'%');
							}
							
							console.log(Data_CustomerArea);
							var Data_OrderType = [];
							for (var i in GetOrderType) {
							  var item = GetOrderType[i];
							  Data_OrderType.push([item["client_req"],item["tj"]]);
						    }
							
							var tj2=0;
							for(var i in Data_OrderType)
							{
								tj2+=Data_OrderType[i][1];
							}
							for(var i in Data_OrderType)
							{
								Data_OrderType[i][1]=Data_OrderType[i][1]/tj2*100;
								
								categories2.push(Highcharts.numberFormat(Data_OrderType[i][1],2)+'%');
							}
							
					        $scope.logining = false;
							
							$scope.chartPie1 = {
							  options: {
								chart: {
								  type: 'bar',
								  // marginTop: '10px'
								} 
							  },
							  xAxis: {
									categories: categories1,
									title: {
										text: null
									}
							  },
							  yAxis: {
								min: 0,
								title: {
									text: '百分比',
									align: 'high'
								},
								labels: {
									overflow: 'justify'
								}
							 },
							  title: {
								text: ''
							  },
							  credits: {
								enabled: false
							  },
							  loading: false
							};
							
							$scope.chartPie1.series = [
							{
								name: '客户来源渠道统计',
								data:Data_CustomerArea,
								type:"bar",
								dataLabels: {enabled: true,format: '{point.name}'},//默认显示x轴的值
								inside:true,
								enableMouseTracking: false  //鼠标移动到上面不显示数量
							}
							];
							
							
							
							$scope.chartPie2 = {
							  options: {
								chart: {
								  type: 'bar',
								  // marginTop: '10px'
								}
							  },
							  xAxis: {
									categories: categories2,
									title: {
										text: null
									}
							  },
							  yAxis: {
								min: 0,
								title: {
									text: '百分比',
									align: 'high'
								},
								labels: {
									overflow: 'justify'
								}
							 },
							  title: {
								text: ''
							  },
							  credits: {
								enabled: false
							  },
							  loading: false
							}
							
							$scope.chartPie2.series = [
							{
								name: '成交订单类别',
								data:Data_OrderType,
								type:"bar",
								dataLabels: {enabled: true,format: '{point.name} '},//默认显示x轴的值
								inside:true,
								enableMouseTracking: false  //鼠标移动到上面不显示数量
							}
							];
        }
    });
  }])
//即时通讯
  .controller('IMCtrl', ['$scope', '$ionicScrollDelegate', '$BPPageModal', '$IM', '$BPFormatDate', function ($scope, $ionicScrollDelegate, $BPPageModal, $IM, $BPFormatDate) {
      var scrollBar = $ionicScrollDelegate.$getByHandle('messageDetailsScroll');
      $scope.vm = {
          "isConnected": false,
          "connectText": "连接服务中...",
          "getHeadImg": function (isOnLine) {
              if (isOnLine == 1) {
                  return "img/on-line.png";
              }
              else {
                  return "img/off-line.png";
              }
          },
          "send_content":""
      }

      $IM.init(function () {//服务断开后处理函数
          $scope.vm.isConnected = false;
          $scope.vm.connectText = "服务器断开";
          $scope.$apply();
      }, $scope).then(function (data) {
          console.log(data,"ctrlim");
          if (data.code == "success") {//连接成功
              $scope.vm.isConnected = true;
          }
          else {
              $scope.vm.isConnected = false;
              $scope.vm.connectText = "连接失败";
          }
      });
      //连接服务成功后执行
      //指定联系人列表
      $scope.imServer = $IM.getServer();
      //格式化时间
      $scope.formatDate = function (date) {
          return $BPFormatDate(date, "MM-dd hh:mm");
      };
      $scope.closeMessageDetailModel = $BPPageModal($scope, 'templates/homeApps/wechat/wechatDetails.html', function (otherUserId) {//打开聊天窗口
          $scope.imServer.currentUserId = otherUserId;
          $scope.imServer.IMGetMsgList(1, 1000, otherUserId).then(function (msglists) {
              //$scope.messages = msglists;
              scrollBar.scrollBottom();
          });
          $scope.imServer.IMUpdateMessageStatus(otherUserId);
          if ($scope.imServer.lastUserList[otherUserId] != undefined)
          {
              $scope.imServer.lastUserList[otherUserId].F_UnReadNum = 0;
          }

      }, function () {
          $scope.imServer.currentUserId = "";
      });


      $scope.sendMsg = function () {
          $scope.imServer.IMSendToOne($scope.imServer.currentUserId, $scope.vm.send_content);
          $scope.vm.send_content = "";
      }

      window.addEventListener("native.keyboardshow", function (e) {
          scrollBar.scrollBottom();
      });

      $scope.scrollBottom = function () {
          scrollBar.scrollBottom();
      };
  }])
//新闻
.controller('NewsCtrl', [
    '$scope', '$BPPageModal', 'News','$BPTriggerRefresh','$timeout','$BPFormatDate','$ionicModal', function ($scope, $BPPageModal, News,$BPTriggerRefresh,$timeout,$BPFormatDate,$ionicModal) {
    $scope.news = News.getList();
	
	//刷新数据
    $timeout(function () {
      $BPTriggerRefresh.triggerRefresh('newslist-content');
    },450);
	
	$scope.doRefresh=function()
	{
		News.update(function () {
			$scope.$broadcast('scroll.refreshComplete');
		});
	}
	$scope.doLoadMore=function()
	{
		console.log('more');
		News.add(function () {
			$scope.$broadcast('scroll.infiniteScrollComplete');
		});
	}
	
    //打开详细页面表
    $scope.openNoticesModal = function (noticeTitle,noticeContent,noticeTime,category) {
		var arrEntities={'lt':'<','gt':'>','nbsp':' ','amp':'&','quot':'"'};
		noticeContent=noticeContent.replace(/&(lt|gt|nbsp|amp|quot);/ig,function(all,t){return arrEntities[t];});
		$scope.noticeContent = noticeContent;
		$scope.noticeTitle = noticeTitle;
		$scope.title=category;
		$scope.noticeDateTime =  $BPFormatDate(noticeTime, "yyyy-MM-dd hh:mm");
        $ionicModal.fromTemplateUrl(('templates/notices/noticeDetails.html'), {
            scope: $scope,
            animation: 'lr-slide-in-right'
        }).then(function (modal) {
            $scope.noticesModal = modal;
            $scope.noticesModal.show();
        });
    };
    $scope.closeNoticesModal = function () {
        $scope.noticesModal.remove();
    };
}])
//通知
.controller('NoticeCtrl', ['$scope','$ionicModal','Notice','$timeout','$BPTriggerRefresh','$BPLocals','$BPFormatDate',function ($scope,$ionicModal,Notice,$timeout,$BPTriggerRefresh,$BPLocals,$BPFormatDate) {
    
	$scope.allNotices=Notice.getList();

	
	//刷新数据
    $timeout(function () {
      $BPTriggerRefresh.triggerRefresh('newslist-content');
    },450);
	
	$scope.doRefresh=function()
	{
		Notice.update(function () {
			$scope.$broadcast('scroll.refreshComplete');
			$scope.notices = $scope.allNotices.notices[$scope.active];
		});
	}
	$scope.doLoadMore=function()
	{
		Notice.add(function () {
			$scope.$broadcast('scroll.infiniteScrollComplete');
			$scope.notices = $scope.allNotices.notices[$scope.active];
		});
	}
	
	
	
    $scope.active = 'btnNoRead';
    $scope.notices = $scope.allNotices.notices[$scope.active];
    $scope.setActive = function(type) {
        $scope.active = type;
        $scope.notices = $scope.allNotices.notices[type];
    };
    $scope.isActive = function(type){
        return type === $scope.active;
    };
	$scope.isEmpty= function(obj)
	{
		for (var name in obj)
		{
			return false;
		}
		return true;
	};
    //打开详情页
    $scope.openNoticesModal = function (noticeTitle,noticeContent,noticeTime,category,noticeId) {
        $ionicModal.fromTemplateUrl(('templates/notices/noticeDetails.html'), {
            scope: $scope,
            animation: 'lr-slide-in-right'
        }).then(function (modal) {
            $scope.noticesModal = modal;
			var arrEntities={'lt':'<','gt':'>','nbsp':' ','amp':'&','quot':'"'};
			noticeContent=noticeContent.replace(/&(lt|gt|nbsp|amp|quot);/ig,function(all,t){return arrEntities[t];});
			$scope.noticeContent = noticeContent;
			$scope.noticeTitle = noticeTitle;
			$scope.title=category;
			$scope.noticeDateTime =  $BPFormatDate(noticeTime, "yyyy-MM-dd hh:mm");	
			var ReadListInfo = $BPLocals.getObject('NoticeReadInfo');

			if($scope.isEmpty(ReadListInfo))
			{
				ReadListInfo={items:[]};
			}
			ReadListInfo.items.push({id:noticeId});
			$BPLocals.setObject('NoticeReadInfo', ReadListInfo);
			//刷新列表数据
			if($scope.allNotices.notices['btnNoRead'].length>0){
				var dataItem=null;
				for (var target_i in $scope.allNotices.notices['btnNoRead'])
				{
					if($scope.allNotices.notices['btnNoRead'][target_i].newsId==noticeId)
					{
						dataItem=$scope.allNotices.notices['btnNoRead'][target_i];
					}
				}
				if(dataItem!=null){
					for(var i=0; i<$scope.allNotices.notices['btnNoRead'].length; i++) {
						if($scope.allNotices.notices['btnNoRead'][i] == dataItem) {
						$scope.allNotices.notices['btnNoRead'].splice(i, 1);
						break;
						}
					}
					$scope.allNotices.notices['btnRead'].push(dataItem);
					$scope.notices = $scope.allNotices.notices[$scope.active];
				}
			}
            $scope.noticesModal.show();
        });
    };
    $scope.closeNoticesModal = function () {
        $scope.noticesModal.remove();
    };
}])

//我的
.controller('PersonCenterCtrl', [
    '$scope', '$state','$BPPageModal', '$BPPopup', '$BPHttp', 'UserInfo', 'ApiUrl','$ionicLoading','$BPTopAlert','md5','$jpushService',
    function ($scope, $state,$BPPageModal, $BPPopup, $BPHttp, UserInfo, ApiUrl,$ionicLoading,$BPTopAlert,md5,$jpushService) {
      $scope.userinfo = UserInfo.get();
	  $scope.f_userinfo = { "mobile": $scope.userinfo.mobile,"telephone": $scope.userinfo.telephone,"email": $scope.userinfo.email,"wechat": $scope.userinfo.wechat,"oicq": $scope.userinfo.oicq,"msn": $scope.userinfo.msn};
	  $scope.pswInfo = {newVarConfirm:'',newVar:'',oldVar:''}; //初始化，重要
      $scope.outLogin = function () {
        $BPPopup.confirm({
          title: '<p> </p>确定要退出登录?<p> </p>',
          okText: '退出',
          ok: function () {
            $BPHttp.post({
              "url": ApiUrl.outLoginApi,
              "success": function (data) {
                //console.log(data);
                UserInfo.clear();
				if($jpushService.check()){
					console.log("设置jpushService");
					$jpushService.setTagsWithAlias([],"");
				}
                $state.go("login");
              },
              "error": function () {
                console.log("error");
                UserInfo.clear();
                $state.go("login");
              }
            });
          },
        });
      };
	  $scope.doModifyUserInfoSubmit=function(){
		  //saveContactInfoApi
		  var ops=$scope.f_userinfo;
		  var mobile=ops.mobile;
		  var telephone=ops.telephone;
		  var email=ops.email;
		  var wechat=ops.wechat;
		  var oicq=ops.oicq;
		  var msn=ops.msn;
		  
		  $ionicLoading.show();
			$BPHttp.post({
              "url": ApiUrl.saveContactInfoApi,
              "data": { "mobile": ops.mobile,"telephone": ops.telephone,"email": ops.email,"wechat": ops.wechat,"oicq": ops.oicq,"msn": ops.msn},
              "isverify": true,
              "success": function (data) {
					UserInfo.update(mobile,telephone,email,wechat,oicq,msn);
					$BPTopAlert.show({ text: data.status.desc });
					$scope.userinfo = UserInfo.get();
              },
			  "finally": function () { 
					$ionicLoading.hide();
			  }
			});
	  }
	  $scope.doModifyPasswordSubmit=function()
	  {
		  var ops=$scope.pswInfo;
		  if(ops.oldVar=='')
		  {
			   $BPTopAlert.show({ text: "请输入原密码" });
		  }
		  else if(ops.newVarConfirm==''||ops.newVar=='')
		  {
			  $BPTopAlert.show({ text: "请输入新的密码" });
		  }
		  else if(ops.newVarConfirm!=ops.newVar)
		  {
			  $BPTopAlert.show({ text: "2次新的密码不同" });
		  }
		  else{
			$ionicLoading.show();
			console.log(ops.oldVar);
			$BPHttp.post({
              "url": ApiUrl.saveModifyPasswordApi,
              "data": { "OldPsw": md5.createHash(ops.oldVar),"NewPsw": md5.createHash(ops.newVar)},
              "isverify": true,
              "success": function (data) {					
					UserInfo.clear();
					$scope.closePageModel();
					$BPTopAlert.show({ text: data.status.desc });
					$state.go("login");
              },
			  "finally": function () { 
					$ionicLoading.hide();
			  }
			});
		  }
	  }
      //打开个人信息列表
      $scope.closePageModel = $BPPageModal($scope,'templates/personCenter/');
}]);
